package com.derbysoft.ota.application.translator.rs;

import com.derbysoft.modules.eip.translator.Translator;
import com.derbysoft.ota.application.translator.CodeTables;
import com.derbysoft.ota.interfaces.protocol._2009a.TaxType;
import com.derbysoft.ota.interfaces.protocol._2009a.TaxesType;
import com.derbysoft.ota.interfaces.protocol._2009a.TotalType;
import com.derbysoft.remote.dswitch.generic.dto.SimpleAmountDTO;
import com.derbysoft.remote.dswitch.hotel.dto.TotalDTO;

public class TotalTranslator implements Translator<TotalDTO, TotalType> {

	@Override
	public TotalType translate(TotalDTO source) {
		TotalType dest = new TotalType();
		
		SimpleAmountDTO sourceTotalAmount = source.getTotalAmount();
		dest.setCurrencyCode(sourceTotalAmount.getCurrency().getCode());
		dest.setAmountAfterTax(sourceTotalAmount.getAmount());
		dest.setAmountBeforeTax(source.getPureAmount().getAmount());
		dest.setAdditionalFeesExcludedIndicator(Boolean.FALSE);
		
		SimpleAmountDTO tax = source.getTax();
		if (tax != null) {
			setTaxesIfRequired(dest);
			dest.getTaxes().getTax().add(tax(tax));
		}
		
		SimpleAmountDTO serviceCharge = source.getServiceCharge();
		if (serviceCharge != null) {
			setTaxesIfRequired(dest);
			dest.getTaxes().getTax().add(serviceCharge(serviceCharge));
		}
		
		SimpleAmountDTO additionalCharge = source.getAdditionalCharge();
		if (additionalCharge != null) {
			setTaxesIfRequired(dest);
			dest.getTaxes().getTax().add(miscellaneous(additionalCharge));
		}
		
		return dest;
	}

	private void setTaxesIfRequired(TotalType dest) {
		if (dest.getTaxes() == null) {
			dest.setTaxes(new TaxesType());
		}
	}

	private TaxType tax(SimpleAmountDTO tax) {
		return of(tax, CodeTables.FTT_STANDARD);
	}

	private TaxType of(SimpleAmountDTO tax, String code) {
		TaxType taxType = new TaxType();
		taxType.setAmount(tax.getAmount());
		taxType.setCurrencyCode(tax.getCurrency().getCode());
		taxType.setCode(code);
		return taxType;
	}
	
	private TaxType serviceCharge(SimpleAmountDTO serviceCharge) {
		return of(serviceCharge, CodeTables.FTT_SERVICE_CHARGE);
	}

	private TaxType miscellaneous(SimpleAmountDTO additionalCharge) {
		return of(additionalCharge, CodeTables.FTT_MISCELLANEOUS);
	}
	
}
